<template>
    <div class="list-wrapper">
        <Block>
            <DataGrid :auto-load="autoLoad" row-key="id" border ref="dataGridRef" showSelection>
                <template #toolbar-search>
                    <div class="query-from-box">
                        <el-form>
                            <el-form-item>
                                <el-input v-model="queryData.productKey" placeholder="产品名称/标识符" clearable />
                            </el-form-item>
                            <el-form-item>
                                <el-select v-model="queryData.productType" placeholder="产品类型" clearable>
                                    <el-option
                                        v-for="(value, key) in ProductType"
                                        :label="value"
                                        :key="key"
                                        :value="key"
                                    />
                                </el-select>
                            </el-form-item>
                            <el-form-item>
                                <el-tree-select
                                    placeholder="产品标签"
                                    v-model="queryData.labels"
                                    :data="labelTree"
                                    :props="defaultProps"
                                    multiple
                                    collapse-tags
                                    collapse-tags-tooltip
                                    check-strictly
                                    :render-after-expand="false"
                                    show-checkbox
                                    clearable
                                    node-key="labelNo"
                                    @visible-change="getLabelTree"
                                />
                            </el-form-item>
                            <el-form-item>
                                <el-input v-model="queryData.objectDisplayName" placeholder="产品模型" clearable />
                            </el-form-item>
                            <el-form-item>
                                <el-select v-model="queryData.state" placeholder="状态" clearable>
                                    <el-option
                                        v-for="(value, key) in ProductState"
                                        :label="value"
                                        :key="key"
                                        :value="key"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-form>
                    </div>
                </template>
                <template #toolbar-operation>
                    <el-button type="primary" @click="onCreate">新建</el-button>
                </template>
                <el-table-column type="index" label="序号" width="60" align="center" fixed />
                <el-table-column label="产品名称" width="300" fixed>
                    <template #default="scope">
                        <el-button link type="primary" @click="onGoDetail(scope.row)">
                            {{ scope.row.productName }}
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="productNo" label="标识符" width="300" />
                <el-table-column label="产品标签" show-overflow-tooltip>
                    <template #default="scope">
                        {{ scope.row.labelNames ? scope.row.labelNames.join('；') : '' }}
                    </template>
                </el-table-column>
                <el-table-column prop="objectDisplayName" label="产品模型" show-overflow-tooltip />
                <el-table-column label="节点类型" width="95">
                    <template #default="scope">
                        <div class="table-item-tag">
                            <el-tag
                                :type="
                                    scope.row.productType == 'DIRECT'
                                        ? 'success'
                                        : scope.row.productType == 'GATEWAY'
                                          ? 'primary'
                                          : 'warning'
                                "
                                >{{ ProductType[scope.row.productType] }}</el-tag
                            >
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="protocolName" label="通讯协议" show-overflow-tooltip />
                <el-table-column label="注册模式">
                    <template #default="scope">
                        {{ ConnectMode[scope.row.connectMode] }}
                    </template>
                </el-table-column>
                <el-table-column label="状态" width="65">
                    <template #default="scope">
                        <span class="table-item-status" :status="ProductState[scope.row.state]">
                            {{ ProductState[scope.row.state] }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="deviceCount" label="设备数量" width="65" />
                <el-table-column label="操作" width="150" fixed="right">
                    <template #default="scope">
                        <el-button link type="primary" v-if="scope.row.state == 'DISABLED'" @click="onEdit(scope.row)"
                            >修改</el-button
                        >
                        <el-button link type="danger" @click="onDel(scope.row)" v-if="scope.row.state == 'DISABLED'">
                            删除
                        </el-button>
                        <el-button
                            link
                            type="primary"
                            v-if="scope.row.state == 'DISABLED'"
                            @click="onEnable(scope.row)"
                            :loading="loading && loading[scope.row.id]"
                        >
                            启用
                        </el-button>
                        <el-button
                            link
                            type="primary"
                            v-else
                            @click="onDisable(scope.row)"
                            :loading="loading && loading[scope.row.id]"
                        >
                            停用
                        </el-button>
                    </template>
                </el-table-column>
            </DataGrid>
        </Block>
    </div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { IoTProductService, runLabelService } from '@great/services';
import { showPopupBox } from '@great/utils';
import { useRouter } from 'vue-router';
import { ProductState, ProductType, ConnectMode } from '@/utils/constant';
import CreateEditModal from './components/list/CreateEditModal.vue';
import { DataGrid, Block, type DataGridInstance } from '@great/components';
import { checkPermi } from '@/utils/ruoyi';

const router = useRouter();

// 查询条件
const queryData = ref({
    productKey: '',
    state: '',
    labels: [],
    objectDisplayName: '',
    productType: ''
});
const defaultProps = {
    children: 'childLabel',
    label: 'labelName',
    value: 'labelNo'
};
const labelTree = ref();
const loading = ref({});
const dataGridRef = useTemplateRef<DataGridInstance>('dataGridRef');
const autoLoad = reactive({
    debounce: true,
    reloadDeps: [queryData],
    onLoad: async (current, size) => {
        const res = await IoTProductService.getPageProduct({
            current,
            size,
            ...queryData.value,
            labels: queryData.value.labels ? queryData.value.labels.join(',') : null
        });
        loading.value = {};
        return { data: res.data.records, total: res.data.total };
    }
});

// 创建
const onCreate = () => {
    showPopupBox(CreateEditModal, {
        callBack: dataGridRef.value?.refresh
    });
};
// 编辑
const onEdit = row => {
    showPopupBox(CreateEditModal, {
        row,
        callBack: dataGridRef.value?.refresh
    });
};
// 查看详情
const onGoDetail = (row: { id: number }) => {
    if (checkPermi(['iot:product:detail'])) {
        router.push({
            name: 'IoT-product-detail',
            params: {
                id: row?.id
            }
        });
    }
};
// 删除
const onDel = (row: { id: number; productName: string }) => {
    ElMessageBox.confirm(`是否确认删除产品 ${row.productName} ？`, '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(async () => {
            await IoTProductService.delProduct(row?.id as number);
            ElNotification({
                title: '删除成功！',
                type: 'success'
            });
            dataGridRef.value?.refresh();
        })
        .catch(() => {});
};
// 停用
const onDisable = async (row: { id: number }) => {
    loading.value[row.id] = true;
    const res = await IoTProductService.verifyProductDeviceEnable(row?.id as number);
    loading.value[row.id] = false;
    if (res.data) {
        ElNotification({
            title: '该产品下设备正在使用中，不可停用！',
            type: 'error'
        });
    } else {
        ElMessageBox.confirm(`确认将产品及产品下任务全部停用？`, '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
        })
            .then(async () => {
                await IoTProductService.disableProduct(row?.id as number);
                ElNotification({
                    title: '停用成功！',
                    type: 'success'
                });
                dataGridRef.value?.refresh();
            })
            .catch(() => {});
    }
};
// 启用
const onEnable = async (row: { id: number }) => {
    loading.value[row.id] = true;
    const res = await IoTProductService.verifyProductJobState(row?.id as number);
    loading.value[row.id] = false;
    ElMessageBox.confirm(`${res.data}`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(async () => {
            await IoTProductService.enableProduct(row?.id as number);
            ElNotification({
                title: '启用成功！',
                type: 'success'
            });
            dataGridRef.value?.refresh();
        })
        .catch(() => {});
};
// 获取标签
const getLabelTree = async () => {
    if (labelTree.value && labelTree.value.length > 0) return;
    const res = await runLabelService.getLabelTree({ labelTypeNo: 'labelType-producctLabel' });
    labelTree.value = res.data;
};
</script>
<style scoped lang="scss">
.list-wrapper {
    .query-from-box {
        display: flex;
        align-items: center;
        .el-form {
            display: flex;
            .el-form-item {
                margin-bottom: 0;
                width: 192px;
            }
            .el-form-item + .el-form-item {
                margin-left: 10px;
            }
        }
    }
    :deep(.data-grid) {
        .table-item-tag {
            display: flex;
        }
        .table-item-status {
            display: flex;
            align-items: center;
            &::before {
                content: '';
                width: 6px;
                height: 6px;
                display: inline-block;
                border-radius: 50%;
                margin-right: 5px;
            }
        }
        .table-item-status[status='停用'] {
            &::before {
                background-color: #909399;
            }
        }
        .table-item-status[status='启用'] {
            &::before {
                background-color: #67c23a;
            }
        }
    }
}
</style>
